import * as Cesium from 'cesium';
import cesiumExt from "@/plugins/cesiumExt/index.js"
import CesiumNavigation from "./toolsManage/cesium-navigation-es6/viewerCesiumNavigationMixin";
import mapinfo from './toolsManage/mapInfo/mapinfo'
import "cesium/Build/Cesium/Widgets/widgets.css";
import "./styles/main.css"
import './styles/animate.min.css'
import markIcon from "./styles/img/green-河道水文.png"
import waterLayer from "./featureManage/water/waterLayer"
import GltfLoaderPrimitive from "./featureManage/gltfLoaderPrimitive/GltfLoaderPrimitive"
import SupplyManage from "./supplyManage/supplymanage" //供电单元管理
import DisLine from "./distributionLine/disLine"
import "./cesiumExt/cesium-tilesetEffect.js"
import "./extent/materialLine"
import waterGeo from "./geojson/water.json"
import supply from "./geojson/supply.json"

import { buildUrl, supplyUrl, roadUrl } from "@/config/index"
Cesium.Ion.defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI1MjI0NjBhZi0xMDZkLTQyOWUtOTQ3OC1lMjdjZTQ0OGMyYmQiLCJpZCI6MTkyOTcsInNjb3BlcyI6WyJhc3IiLCJnYyJdLCJpYXQiOjE1NzUzMzYzMzR9.ejj73f-8e0bIAzNYNfeCq6_lo7zMDSw4_MVJyIXwV1s"
    // 特效 默认开启
Cesium.TILE_EFFECT_STAYE = true;
Cesium.TILE_FS_BODY = ` float stc_pl = fract(czm_frameNumber / 360.0) * 3.14159265 *         
                 2.0;
                float stc_sd = v_stcVertex.z / 20.0 + sin(stc_pl) * 0.01;
                gl_FragColor *= vec4(stc_sd, stc_sd, stc_sd, 1.0);
                float stc_a13 = fract(czm_frameNumber / 360.0);
                float stc_h = clamp(v_stcVertex.z / 60.0, 0.5, 1.0);
                stc_a13 = abs(stc_a13 - 0.5) * 2.0;
                float stc_diff = step(0.05, abs(stc_h - stc_a13));
                gl_FragColor.rgb += gl_FragColor.rgb * (1.0 - stc_diff);
                `;
// Cesium.TILE_FS_BODY = ` float stc_pl = fract(czm_frameNumber / 120.0) * 3.14159265 *         
//         2.0;
//     float stc_sd = v_stcVertex.z / 50.0 + 0.09;
//     gl_FragColor *= vec4(stc_sd, stc_sd, stc_sd, 1.0);

//     `
// // ;
window.Mapapp = function(domID, mapConfig) {
    this._viewer = new Cesium.Viewer(domID, {
        terrainProvider: Cesium.createWorldTerrain({
            url: "/static/terrain"
        }),
        timeline: false,
        animation: false,
        shouldAnimate: true,
        homeButton: false,
        infoBox: false,
        baseLayerPicker: false,
        geocoder: false,
        navigationHelpButton: false,
        scene3DOnly: true,
        fullscreenButton: false,
        terrainExaggeration: 1
    });
    if (Cesium.FeatureDetection.supportsImageRenderingPixelated()) { //判断是否支持图像渲染像素化处理
        this._viewer.resolutionScale = window.devicePixelRatio;
    }
    //是否开启抗锯齿
    this._viewer.scene.fxaa = true;
    this._viewer.scene.postProcessStages.fxaa.enabled = true;
    CesiumNavigation(this._viewer, {});
    new mapinfo(this._viewer)
    this.GltfManage = new GltfLoaderPrimitive(this._viewer, Cesium)
    this.supplyManage = new SupplyManage(this._viewer, Cesium)
    this.supplyManage.init()
    this.disLine = new DisLine(this._viewer, Cesium)
    this.disLine.init()

    // let overviewMap = new OverviewMap(this._viewer)
    // materialLine({flowImage:flowImg})
    // mapbox://styles/cygis2011/ckixzyf173ym919lfdeda8zl9
    // mapbox://styles/cygis2011/ckd7f9y7k0ve71ip5wgzoxi7p
    // mapbox://styles/cygis2011/ckixzyf173ym919lfdeda8zl9
    var mapboxlayer = new Cesium.MapboxStyleImageryProvider({
        url: 'https://api.mapbox.com/styles/v1/',
        username: 'cygis2011',
        styleId: 'ckixzyf173ym919lfdeda8zl9',
        accessToken: 'pk.eyJ1IjoiY3lnaXMyMDExIiwiYSI6ImNqNGFsb245aTAxaGwzM3Bud3lhd3U2NnUifQ.695fY9okFMdI81Afs9I19g',
        scaleFactor: true
    });

    var darkMap = new Cesium.WebMapTileServiceImageryProvider({
        url: 'http://113.240.224.29:8062/gis-iserver/Map/vec/google-all-img/{TileMatrix}/{TileCol}/{TileRow}',
        layer: 'googleMap',
        style: 'default',
        format: 'image/jpeg',
        tileMatrixSetID: 'default028mm',
        maximumLevel: 19,
        credit: new Cesium.Credit('chenyugis')
    });
    Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(108.4269, 23.2627, 114.4369, 29.2827); //homebutton默认跳转位置
    this._viewer.scene.imageryLayers.removeAll();
    // this._viewer.scene.imageryLayers.addImageryProvider(darkMap);
    this._viewer.scene.imageryLayers.addImageryProvider(mapboxlayer);
    this._viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);

    //设置地图可缩放级别
    this._viewer.scene.screenSpaceCameraController.minimumZoomDistance = 10;
    this._viewer.scene.screenSpaceCameraController.maximumZoomDistance = 65000000;
    this._viewer.scene.globe.depthTestAgainstTerrain = true;

    this.add3DTiles(buildUrl, true, true)
        // var tile3D2 = this.add3DTiles(grassUrl, true,true)

    // this.addMark({ lon: 112.939658032000000, lat: 28.226638709300001 }, { name: "变电站" }, 1)
    // this.addMark({ lon: 113.4229, lat: 29.3067 }, { name: "停车场2" }, 1)
    this.addRoad()
        // this.drawEnclosure()
        // this.addriver()
        // this.GltfManage.addGltfPrimitive({
        //     gltfUrl: "/static/gltf/变电站.gltf",
        //     scale: 1,
        //     lon: 112.9240,
        //     lat: 28.2085,
        //     height: 30,
        //     id: "111"
        // })
    this.bind_evt()

}
window.Mapapp.prototype = {
    resize: function() {
        this._viewer.resize()
    },
    bind_evt: function() {
        var self = this
        this.handler = new Cesium.ScreenSpaceEventHandler(this._viewer.scene.canvas);
        this.handler.setInputAction(function(movement) {            
            var pick = self._viewer.scene.pick(movement.position);            
            if (Cesium.defined(pick) && pick.id) {
                if (pick.id.click) {
                    pick.id.click()
                    pick.id.polyline.material = Cesium.PolylineGlowMaterialProperty({
                        glowPower: 0.2,
                        color: Cesium.Color.DARKCYAN.withAlpha(0.9)
                    })
                    if (self.selectLine) {
                        self.selectLine.polyline.material = self.selectLine.defaultMaterial
                    }
                    self.selectLine = pick.id
                }
            } else {
                // self.infoWindow.close()
                if (self.selectLine) {
                    self.selectLine.polyline.material = self.selectLine.defaultMaterial
                }
            }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
    },
    add3DTiles(url, zoomTo, isshow) {
        var self = this
        var nonClassificationTileset = new Cesium.Cesium3DTileset({
            url: url,
            show: true,
            maximumScreenSpaceError: 16,
            skipLevelOfDetail: false,
            preloadFlightDestinations: true,
            maximumMemoryUsage: 2048,
            // material: new materialWall()
            // debugWireframe:true
            // classificationType: ClassificationType.BOTH,
        });
        nonClassificationTileset.readyPromise.then(function(tileset) {
            tileset.show = isshow
            tileset.style = new Cesium.Cesium3DTileStyle({
                color: {
                    conditions: [
                        // ["(${height} >= 60.0)", "color('darkcyan')"],
                        // ["(${height} >= 40.0)", "color('darkcyan')"],
                        // ["(${height} < 40.0)", "color('cyan')"],
                        ["true", "color('darkcyan',1.0)"]
                    ]
                }
            });
            self._viewer.scene.primitives.add(tileset);

            if (zoomTo) {
                self._viewer.zoomTo(tileset)
            }
        }).otherwise(function(error) {
            console.log(error)
            return null
        });
        return nonClassificationTileset
    },

    addMark(mark) {
        // 删除变电站
        this._viewer.entities._entities._array.map(obj => {
            if (obj.id == mark.id) {
                this._viewer.entities.remove(obj);
            }
        })
        var self = this
        var hpoint = null
        var positions = [
            Cesium.Cartographic.fromDegrees(mark.lon, mark.lat),
        ];

        var promise = Cesium.sampleTerrainMostDetailed(this._viewer.terrainProvider, positions);
        Cesium.when(promise, function(updatedPositions) {
            var terrainHeight = updatedPositions[0].height
            hpoint = Cesium.Cartesian3.fromDegrees(mark.lon, mark.lat, terrainHeight);
            console.log('坐标', hpoint)
            var entity = {
                position: hpoint,
                model: {
                    uri: mark.gltfUrl,
                    // eyeOffset: new Cesium.Cartesian3(0.0, 20.0, -10.0),
                    // disableDepthTestDistance: Number.POSITIVE_INFINITY,
                    // // scaleByDistance: new Cesium.NearFarScalar(18000, 1, 100000, 0),
                    // // heightReference:HeightReference.CLAMP_TO_GROUND,
                    // pixelOffset: new Cesium.Cartesian2(20, -36),
                    scale: mark.scale
                },
                id: mark.id,

                label: new Cesium.LabelGraphics({
                    text: mark.name,
                    font: '14px sans-serif',
                    fillColor: new Cesium.Color(1, 1, 1, 1),
                    // fillColor :Cesium.Color.DARKMAGENTA,
                    // fillColor: Cesium.Color.fromCssColorString('#d3d'),
                    outlineWidth: 2,
                    showBackground: true,
                    style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                    eyeOffset: new Cesium.Cartesian3(0.0, 20.0, 0.0),
                    backgroundColor: new Cesium.Color(0.1, 0.1, 0.1, 0.8),
                    verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                    horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                    pixelOffset: new Cesium.Cartesian2(20, -88),
                    // scaleByDistance: new Cesium.NearFarScalar(18000, 1, 100000, 0),
                    disableDepthTestDistance: 2000000,
                    // heightReference:HeightReference.CLAMP_TO_GROUND
                })
            }
            self._viewer.entities.add(entity)
                // 跳转
            self.getTo(mark.id)
        })

    },
    addRoad() {
        var self = this
        this.RoadMap = new Map();
        var promise = Cesium.GeoJsonDataSource.load(roadUrl, { clampToGround: true });
        promise.then(function(dataSource) {
            self._viewer.dataSources.add(dataSource);
            var entities = dataSource.entities.values;
            for (var i = 0; i < entities.length; i++) {
                var entity = entities[i];
                // self.RoadMap.set(entity._properties.gml_id._value,entity)
                entity.polyline.width = 6
                entity.polyline.material = new Cesium.PolylineTrailLinkMaterialProperty(new Cesium.Color(0.1, 0.2, 0.3, 0.5), 3000)
            }
        });
    },
    addWater() {
        var self = this
        waterGeo.geometries.forEach(featur => {
            var poins = []
            featur.coordinates[0].forEach(coor => {
                poins = poins.concat(coor)
            })
            poins.shift()
            poins.shift()
            var waterL = new waterLayer(poins, null, 1)
            waterL.addTo(self._viewer.scene)
        })
    },
    drawEnclosure: function() {
        var self = this
        supply.features.forEach(featur => {
            var poins = []
            var heights = []
            featur.geometry.coordinates[0].forEach(coor => {
                poins = poins.concat(coor)
                heights.push(150)
            })
            let posct3 = Cesium.Cartesian3.fromDegreesArray(poins)
            var point = {
                key: "enclosure",
                wall: {
                    positions: posct3,
                    maximumHeights: heights,
                    // material:Color.fromRandom({ alpha: 0.7 })
                    material: new materialWall()
                }
            }
            this._viewer.entities.add(point)
        })
    },
    addModel() {
        var point = {
            key: "enclosure",
            polyline: {
                positions: posct3,
                clampToGround: true,
                width: 2,
                material: Cesium.Color.fromCssColorString('#ff0').withAlpha(1),
            },
            wall: {
                positions: posct3,
                maximumHeights: heights,
                // material:Color.fromRandom({ alpha: 0.7 })
                material: new materialWall()
            }
        }
        this._viewer.entities.add(point)
    },
    // 隐藏实体
    removeEntity(id, s) {
        console.log(s)
        var buildentity = this.GltfManage.getGltfById(id)
        buildentity.show = s
    },
    // 根据ID查询到实体类再根据flyTo定位到实体
    getTo(station) {
        // console.log(id)

        var buildentity = this._viewer.entities.getById(station)
        console.log(station)
        this._viewer.flyTo(buildentity, {
            offset: {
                heading: Cesium.Math.toRadians(0.0),
                pitch: Cesium.Math.toRadians(-45),
                range: 200
            }

        });
        // if (station) {
        //     var hpoint = Cesium.Cartesian3.fromDegrees(station.lon, station.lat, 100);
        //     this._viewer.camera.flyTo({
        //         destination: hpoint,
        //         orientation: {
        //             heading: Cesium.Math.toRadians(0),
        //             pitch: Cesium.Math.toRadians(-50),
        //             roll: 0.0
        //         }
        //     })
        // }

    },
    //新增实体
    addEntity(Entity) {
        // const a = {
        //         gltfUrl: Entity.gltfUrl,
        //         scale: Entity.scale,
        //         lon: Entity.lon,
        //         lat: Entity.lat,
        //         height: Entity.height || 50,
        //         id: Entity.id
        //     }
        // this.GltfManage.addGltfPrimitive(a)
        this.addMark(Entity)


    },
    //展示供电单元
    showsupply(id) {
        this.supplyManage.show(id)
    }
}
export default Mapapp